<template>
  <div class="users-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <span>用户管理</span>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>

      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名或邮箱"
          style="width: 300px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <el-table
        :data="filteredUsers"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="phone" label="电话" width="130" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)">编辑</el-button>
            <el-button size="small" @click="showRoleDialog(row)">角色</el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="isEdit ? '编辑用户' : '添加用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveUser" :loading="saving">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 角色分配对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      title="分配角色"
      width="400px"
    >
      <el-checkbox-group v-model="selectedRoles">
        <el-checkbox
          v-for="role in allRoles"
          :key="role.id"
          :label="role.id"
        >
          {{ role.name }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="roleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveRoles" :loading="savingRoles">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userApi } from '@/api/user'

export default {
  name: 'Users',
  setup() {
    const loading = ref(false)
    const saving = ref(false)
    const savingRoles = ref(false)
    const users = ref([])
    const allRoles = ref([])
    const searchKeyword = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    
    const userDialogVisible = ref(false)
    const roleDialogVisible = ref(false)
    const isEdit = ref(false)
    const currentUser = ref(null)
    const selectedRoles = ref([])

    const userForm = reactive({
      username: '',
      email: '',
      realName: '',
      phone: '',
      password: '',
      status: 'active'
    })

    const userRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    }

    const filteredUsers = computed(() => {
      if (!searchKeyword.value) return users.value
      return users.value.filter(user => 
        user.username.includes(searchKeyword.value) ||
        user.email.includes(searchKeyword.value)
      )
    })

    const loadUsers = async () => {
      loading.value = true
      try {
        // 模拟API调用
        const mockUsers = [
          {
            id: 1,
            username: 'admin',
            email: 'admin@school.com',
            realName: '管理员',
            phone: '13800138000',
            status: 'active',
            createTime: '2024-01-01 10:00:00'
          },
          {
            id: 2,
            username: 'teacher1',
            email: 'teacher1@school.com',
            realName: '张老师',
            phone: '13800138001',
            status: 'active',
            createTime: '2024-01-02 10:00:00'
          }
        ]
        users.value = mockUsers
        total.value = mockUsers.length
      } catch (error) {
        ElMessage.error('加载用户列表失败')
      } finally {
        loading.value = false
      }
    }

    const loadRoles = async () => {
      try {
        // 模拟角色数据
        allRoles.value = [
          { id: 1, name: '管理员' },
          { id: 2, name: '教师' },
          { id: 3, name: '学生' }
        ]
      } catch (error) {
        ElMessage.error('加载角色列表失败')
      }
    }

    const showAddDialog = () => {
      isEdit.value = false
      Object.assign(userForm, {
        username: '',
        email: '',
        realName: '',
        phone: '',
        password: '',
        status: 'active'
      })
      userDialogVisible.value = true
    }

    const showEditDialog = (user) => {
      isEdit.value = true
      currentUser.value = user
      Object.assign(userForm, {
        username: user.username,
        email: user.email,
        realName: user.realName,
        phone: user.phone,
        status: user.status
      })
      userDialogVisible.value = true
    }

    const showRoleDialog = (user) => {
      currentUser.value = user
      selectedRoles.value = user.roles || []
      roleDialogVisible.value = true
    }

    const handleSaveUser = async () => {
      try {
        await userFormRef.value.validate()
        saving.value = true
        if (isEdit.value) {
          // 更新用户
          await userApi.updateUser(currentUser.value.id, userForm)
          ElMessage.success('用户更新成功')
        } else {
          // 创建用户
          await userApi.createUser(userForm)
          ElMessage.success('用户创建成功')
        }
        userDialogVisible.value = false
        loadUsers()
      } catch (error) {
        ElMessage.error('操作失败')
      } finally {
        saving.value = false
      }
    }

    const handleSaveRoles = async () => {
      try {
        savingRoles.value = true
        // 保存角色分配
        ElMessage.success('角色分配成功')
        roleDialogVisible.value = false
      } catch (error) {
        ElMessage.error('角色分配失败')
      } finally {
        savingRoles.value = false
      }
    }

    const handleDelete = async (user) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除用户 "${user.username}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        ElMessage.success('用户删除成功')
        loadUsers()
      } catch {
        // 用户取消
      }
    }

    const handleSearch = () => {
      currentPage.value = 1
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      loadUsers()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      loadUsers()
    }

    onMounted(() => {
      loadUsers()
      loadRoles()
    })

    return {
      loading,
      saving,
      savingRoles,
      users,
      allRoles,
      searchKeyword,
      currentPage,
      pageSize,
      total,
      userDialogVisible,
      roleDialogVisible,
      isEdit,
      currentUser,
      selectedRoles,
      userForm,
      userRules,
      filteredUsers,
      showAddDialog,
      showEditDialog,
      showRoleDialog,
      handleSaveUser,
      handleSaveRoles,
      handleDelete,
      handleSearch,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.users-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 